# -*- coding: utf-8 -*-
"""
Created on Wed Mar  7 11:04:15 2018

@author: markli
"""
import numpy as np;
from PIL import Image;
import matplotlib.pyplot as pyplot;
class ImageFilter:
    def __init__(self,filepath):
        self.path = filepath;

    def Filter(self,filtermatrix):
        """步长设定为1"""
        img = Image.open(self.path);
        #img = img.resize((32,32));
        r,g,b = img.split(); #rgb 通道分离
        #转为数字矩阵
        r_arr = np.array(r);
        g_arr = np.array(g);
        b_arr = np.array(b);

        matrix = [r_arr,g_arr,b_arr];
        #过滤后的结果矩阵
        fm = np.ones((r_arr.shape[0] - filtermatrix.shape[0] + 1,r_arr.shape[1] - filtermatrix.shape[1]+1));
        fm_rgb = [];
        #卷积运算 实现过滤
        for m in matrix:
            row = 0;
            for i in range(fm.shape[0]):
                col = 0;
                for j in range(fm.shape[1]):
                    temp = m[row:row + filtermatrix.shape[0],col:col + filtermatrix.shape[1]];
                    fm[i][j] = np.sum(np.multiply(temp,filtermatrix));
                    col = col + 1;
                row = row + 1;

            fm_rgb.append(fm);

        return fm_rgb;
#        #数字矩阵转为RGB通道像素
#        r = Image.fromarray(fm_rgb[0]).convert('L');
#        g = Image.fromarray(fm_rgb[1]).convert('L');
#        b = Image.fromarray(fm_rgb[2]).convert('L');
#        image = Image.merge("RGB", (r, g, b));
#        #图片显示
#        pyplot.imshow(image);
#        pyplot.show();
    def MergeEdage(self,savepath):
        leftmatrix = np.array([[1,0,-1],[1,0,-1],[1,0,-1]]);#左边界
        left = self.Filter(leftmatrix);
        rightmatrix = np.array([[-1,0,1],[-1,0,1],[-1,0,1]]);#右边界
        right = self.Filter(rightmatrix);
        w_1,h_1 = left[0].shape; #left 和 right 维数相同，使用哪个都可以
        full_edage = [];
        for i in range(3):
            m = np.hstack((left[i][:,:int(w_1/2)],right[i][:,w_1-int(w_1/2):]));
            full_edage.append(m);

        #数字矩阵转为RGB通道像素
        r = Image.fromarray(full_edage[0]).convert('L');
        g = Image.fromarray(full_edage[1]).convert('L');
        b = Image.fromarray(full_edage[2]).convert('L');
        image = Image.merge("RGB", (r, g, b));
        #图片显示
        pyplot.imshow(image);
        pyplot.show();
        image.save(savepath);

img = ImageFilter("02.jpg");
img.MergeEdage("021.jpg");